﻿//定义应用全局对象
window.ABUS = {
    Const: {
        param: "__param__",
        result: "__result__",
        result_param: "result_param"
    },
    Fn: {},
    env: "prd"//dev:开发 prd：生产,
};

//初始化
$(function () {
    //设置常用对象引用
    var abus = ABUS;
    var fn = abus.Fn;
    var Const = abus.Const;
    var $body = $(document.body);
    var _root_ = "http://www.carzki.cn/";
    // var _root_ = "http://112.74.47.132:38080/";
    window.isDrag = false;

    (function () {
        if (!window[ABUS.Const.param]) {
            window[ABUS.Const.param] = {}
        }
        //初始化传参
        // var __param__ = window[ABUS.Const.param] = __param__?__param__:{};
        var url = window.location.href
            , start = url.indexOf("?") == -1 ? null : url.indexOf("?") + 1
            , end = url.indexOf("#")
            , param;
        if (end == -1) {
            param = url.slice(start);
        } else {
            param = url.slice(start, end);
        }
        if (param.search('=') > -1) {
            param = param.split("&");
            $.each(param, function (i, j) {
                window[ABUS.Const.param][j.split('=')[0]] = decodeURIComponent(j.split('=')[1]);
            });
        }
    })();

    //监听窗口改变事件，重新计算跟字体大小
    $(window).on('resize', function () {
        $('html').css({
            'font-size': 100 * ($(window).width() / 375)
        })
    }).trigger('resize');

    $(window).on('unload', function () {
        // if(window[Const.result]){
        fn.winClose();
        // }
    });

    $.fn.renderTemp = function (data) {
        var that = this;
        var tp = $.trim(that.children("script[type='text/template']:first").html());

        if (!that.data('tp') && tp != '') {
            that.data('tp', tp);
        }

        this.html(function () {
            return _.template(that.data('tp'))(data)
        })
    };

    //监听点击事件，关闭视窗浮层
    $body.on("touchend", ".main_modal_wrap", function () {
        fn.closeModal();
    });

    //通用ajax
    fn.get = function (options) {
        var url = options.url ? _root_ + options.url : './simdata/common.json';
        // if (abus.env == 'prd') {
        //     url = url.substr(url.lastIndexOf('/') + 1).replace(/_/g, "/").replace(".json", "");
        // }
        var data = options.data ? options.data : {};
        var success = options.success ? options.success : _.noop;
        var _success = function (data) {
            if(data.message && data.message.search(/登录失败|登陆失败/)>-1){
                fn.alert({
                    type:"error",
                    title:"请重新登录"
                });
                setTimeout(function () {
                    fn.page_goto({
                        url:"/wwwroot/denglu/denglu.html"
                    })
                },1500);
            }
            success(data);
        }
        var error = options.error ? options.error : _.noop;
        // var type = options.type ? $.trim(options.type).toLowerCase() : 'get';

        // if (type == 'post') {
        //     $.post(url, data, success, 'json');
        // } else if (type == 'put') {
        //     $.ajax({
        //         url: url,
        //         data: data,
        //         success: success,
        //         dataType: 'json',
        //         type: type
        //     });
        // } else {
        //     $.getJSON(url, data, success);
        // }
        if (abus.env == 'prd') {
            $.ajax({
                url: url,
                data: data,
                success: _success,
                error:error,
                dataType: 'jsonp'
            });
        }else{
            $.getJSON(url, data, _success);
        }
    };

    //关闭遮罩层后移除节点
    fn.closeModal = function (cb) {
        if ($('.main_modal_wrap:first').find("[unhide]").length > 0) return false;
        $('.main_modal_wrap:first').fadeOut('fast', function () {
            $(this).remove();
            cb ? cb() : null
        })
    };

    //模态框父类
    var Modal = function (options) {
        var that = this;
        this.$el = $("<div class='main_modal_wrap'></div>");
        //遮罩层模板
        var tp_mask = _.template('<div class="main_modal_inner" style="<%=!mask?\"background:none;\":\"\"%>"><%=content%></div>');
        //遮罩层接口
        this.doMask = function (options) {
            //合并配置
            // _.defaults(options, {
            // });
            //加载到页面
            this.$el.html(tp_mask(options));
            $body.append(this.$el);
            //显示
            this.$el.fadeIn('fast', function () {
                _.isFunction(options.onShow) ? options.onShow.call(that.$el) : null;
            });
        };
        this.mask = _.isUndefined(options.mask) ? true : options.mask;
        this.options = options;
        this.template = options.template;

        this.$el.on('click', '[data-submit-btn]', function () {
            _.isFunction(options.onSubmit) ? options.onSubmit.call(that.$el) : null;
        });
        this.$el.on('click', '[data-cancel-btn]', function () {
            _.isFunction(options.onCancel) ? options.onCancel.call(that.$el) : null;
        });
        return this;
    };
    Modal.prototype.show = function () {
        fn.closeModal();
        //调用遮罩层
        this.doMask($.extend({
            content: this.template({
                data: this.options
            }),
            mask: this.mask
        }, this.options));
        return this;
    };

    //操作结果提示层模板
    var tp_alert = _.template('' +
        '<%if(data.type == "success"){%>' +
        '<div class="payment_success radius_small">' +
        '<%}else{%>' +
        '<div class="payment_failed radius_small">' +
        '<%}%>' +
        '<span class="font20 colorfff"><%=data.title%></span>' +
        '</div>');
    //操作结果提示层接口
    fn.alert = function (options) {
        //合并配置
        if (options.type != "success" && options.type != "error") {
            console.error("类型错误");
            return;
        }
        options.title = options.title ? options.title : "";
        options.template = tp_alert;
        options.onShow = options.onShow ? options.onShow : function () {
                setTimeout(function () {
                    fn.closeModal();
                }, 1000)
            };
        //调用遮罩层
        new Modal(options).show();
    };

    fn.loading = function (options) {
        options = options ? options : {};
        options.title = options.title ? options.title : "";
        options.mask = false;
        options.template = _.template('<div class="g_loading">加载中...</div>');
        options.onShow = options.onShow ? options.onShow : function () {
            };
        //调用遮罩层
        new Modal(options).show();
    };
    //微信支付提示层模板
    var tp_payment = _.template('\
        <div class="chat_payment radius_small">\
        <div class="payment_top">\
        <span class="font14 color284">确认结算</span>\
        </div>\
        <div class="payment_mid">\
        <span class="font18 color284">结算订单金额</span>\
        <span class="font18 colorf29 num">--.--</span>\
        <span class="font18 color284">元</span>\
        </div>\
        <div class="payment_bottom">\
        <div class="payment_bottom_left radius_big" data-cancel-btn>\
        <a class="font14 colorfff">取消</a>\
        </div>\
        <div class="payment_bottom_right radius_big" data-submit-btn>\
        <a class="font14 colorfff">确定</a>\
        </div>\
        </div>\
        </div>');
    //微信支付提示层接口
    fn.payment = function (options) {
        /*  options.template = tp_payment;*/
        options = $.extend({
            onShow: function () {
                var self = this;
                $(this).find(".num").text(options.price?options.price:0);
                $(this).on("touchend ", function (e) {
                    e.stopPropagation();
                });
            }
        }, options);

        options.template = options.template ? _.template(options.template) : tp_payment;
        //调用遮罩层
        new Modal(options).show();

    };
    //确认层模板
    var tp_confirm = _.template('\
        <div class="chat_payment radius_small">\
        <div class="payment_top">\
        </div>\
        <div class="payment_mid">\
        <span class="font18 color284"><%=data.title?data.title:"确认执行此操作？"%></span>\
        </div>\
        <div class="payment_bottom">\
        <div class="payment_bottom_left radius_big" data-cancel-btn>\
        <a class="font14 colorfff">取消</a>\
        </div>\
        <div class="payment_bottom_right radius_big" data-submit-btn>\
        <a class="font14 colorfff">确定</a>\
        </div>\
        </div>\
        </div>');
    //微信支付提示层接口
    fn.confirm = function (options) {
        /*  options.template = tp_confirm;*/
        options = $.extend({
            onShow: function () {
                var self = this;
                $(this).find(".num").text(options.price?options.price:0);
                $(this).on("touchend ", function (e) {
                    e.stopPropagation();
                });
            }
        }, options);

        options.template = options.template ? _.template(options.template) : tp_confirm;
        //调用遮罩层
        new Modal(options).show();

    };
    //静态信息提示层模板
    var tp_info = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.info = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_info;
        //调用遮罩层
        new Modal(options).show();
    };
    //滚动选择层接口
    fn.scrollSelect = function (options) {
        // options.template = tp_timeselect;
        //调用遮罩层
        // new Modal(options).show();
        //api:https://docs.mobiscroll.com/2-17-3/jquery/scroller#usage
        var id = options.id;
        if (!id) return;

        var mobiscrollInst = $(id).mobiscroll('getInst');
        if (mobiscrollInst._class == 'scroller') return true;
        $(id).mobiscroll('destroy').scroller(options);
        mobiscrollInst = $(id).mobiscroll('getInst');
        mobiscrollInst.show();
        return mobiscrollInst;
    };
    //日历模板
    var tp_calendar = _.template('\
        <div class="calendar_list radius_big">\
        <div class="cal1"></div>\
   </div>');
    fn.calendar = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_calendar;
        //调用遮罩层
        new Modal(options).show();
    };


    //页面跳转传参
    fn.page_goto = function (options, callback) {
        var url = options.url;
        if (options.data) {
            url += '?' + $.param(options.data);
        }
        //有回调模式
        if (callback) {
            // var _win = window.open(options.url);
            // _win[Const.param] = options.data;
            window[Const.result] = function (data) {
                callback ? callback(data) : null;
            };
            var ifr = $("<iframe></iframe>");
            ifr.css({
                width: '100%',
                height: '100%',
                border: "1px ",
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: 999
            });
            ifr.prop('src', url + '?v=' + new Date().getTime());
            $('body').append(ifr);
            $('html').css('overflow-y', 'hidden');
            $('.header').hide();
        } else {
            //无回调模式
            // var url = window.location.href.split('?')[0];
            // var url = options.url;
            // if(options.data){
            //     url += '?' + $.param(options.data);
            // }
            window.location.href = url;
        }
    };

    //页面跳转传参
    fn.open_url = function (options, callback) {
        var url = window.location.href.split('?')[0];
        url += '?' + $.param(options.data);
        window.location.href = url;
    };

    //设置关闭回调
    fn.setResult = function (val) {
        window[Const.result_param] = val;
    };

    //窗口关闭
    fn.winClose = _.debounce(function () {
        if (_.isFunction(window.parent[Const.result])) {
            window.parent[Const.result](window[Const.result_param])
        } else {

        }
        setTimeout(function () {
            window.parent.$('.header').show();
            window.parent.$('html').css('overflow-y', 'auto');
            window.parent.$('iframe').remove();
        }, 0);
        return;
    }, 100, true);

    //倒计时
    fn.countDown = function (min, cb) {
        var time = parseInt(min,10) * 60;
        var timer = window.setInterval(function () {
            if(time === 0){
                window.clearInterval(timer);
                return false;
            }
            time--;
            cb(Math.floor(time/3600) + ':' + Math.floor(time%3600/60) + ':' + Math.floor(time%60),Math.ceil(time/60))
        },1000);
        return '';
    };

    //生成随机数
    fn.getNonceStr = function () {
        var s = '', i = 0;
        for (i; i <= 31; i++) {
            s += parseInt(Math.random() * 16, 10).toString(16)
        }
        return s.toUpperCase();
    };

    fn.getTimeStamp = function () {
        return new Date().getTime().toString().slice(0, 10)
    };

    fn.wxPay = function (options) {
        //支付按钮
        var btnId = options.btnId;
        var priceId = options.priceId;
        var orderType = options.orderType;
        var body = options.body;
        var success = options.success;
        var fail = options.fail;
        var fn = window.ABUS.Fn;
        var location = window.location;
        var appId = 'wx60560b337cffe410';
        fn.get({
            // url: "../../../simdata/_wechart_getSignature.json",
            url:"/wechart/getSignature",
            data: {
                "url": location.origin + location.pathname + location.search,
                "timestamp": fn.getTimeStamp(),
                "noncestr": fn.getNonceStr()
            },
            success: function (data) {
                if (data.result !== 1) {
                    fn.alert({
                        type:"error",
                        title:data.message
                    });
                    return false;
                }
                data = data.data;

                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: appId, // 必填，公众号的唯一标识
                    timestamp: fn.getTimeStamp(),//data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: fn.getNonceStr(),//data.noncestr, // 必填，生成签名的随机串
                    signature: data.signature,// 必填，签名，见附录1
                    jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });
                initPay(wx);
            }
        });

        function initPay(wx) {
            wx.ready(function () {
                $(document.body).on('touchstart', '#' + btnId, function () {
                    var timeStamp = fn.getTimeStamp();
                    var nonceStr = fn.getNonceStr();
                    var price = $.trim($('#' + priceId).text()) ? $.trim($('#' + priceId).text()) : '0';
                    fn.get({
                        url: "../../../simdata/_wechart_prePayRequest.json",
                        // url:"/wechart/prePayRequest",
                        type: "post",
                        data: {
                            "orderType": orderType,
                            "body": body,
                            "orderPrice": price,
                            "timeStamp": timeStamp,
                            "nonceStr": nonceStr
                        },
                        dataType: "json",
                        success: function (data) {
                            if (data.result !== 1) {
                                fn.alert({
                                    type: "error",
                                    title: data.message
                                });
                                fn.closeModal();
                                return false;
                            }
                            data = data.data;
                            //创建支付
                            fn.get({
                                url: "../../../simdata/_wechart_getPaySign.json",
                                // url: "/wechart/getPaySign",
                                type: "post",
                                data: {
                                    "appId": appId,
                                    "timeStamp": timeStamp,
                                    "nonceStr": nonceStr,
                                    "prepay_id": "prepay_id=" + data.prepay_id,
                                    "signType": 'MD5'
                                },
                                dataType: "json",
                                success: function (data1) {
                                    data1 = data1.data;
                                    WeixinJSBridge.invoke(
                                        'getBrandWCPayRequest', {
                                            "appId": data1.appId,
                                            "timeStamp": data1.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                            "nonceStr": data1.nonceStr, // 支付签名随机串，不长于 32 位
                                            "package": data1.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                                            "signType": data1.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                                            "paySign": data1.sign, // 支付签名
                                        },
                                        function (res) {
                                            // var s_res = JSON.stringify(res);
                                            if (res.err_msg == "get_brand_wcpay_request:ok") {
                                            // if(s_res.search('ok') !== -1){
                                                success ? success(res) : null
                                            } else {
                                                fail ? fail(res) : null
                                            }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                        }
                                    );
                                }
                            })
                        }
                    });
                })
            });
            wx.error(function (res) {
                console.log('config error');
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });
        }

    };

    fn.getSign = function (options, cb) {
        var fn = window.ABUS.Fn;
        var location = window.location;
        var appId = 'wx9e3a408718504321';
        var apiList = options.apiList ? options.apiList : [];
        fn.get({
            // url: "../../../simdata/_wechart_getSignature.json",
            url:"/wechart/getSignature",
            data: {
                "url": location.origin + location.pathname + location.search,
                "timestamp": fn.getTimeStamp(),
                "noncestr": fn.getNonceStr()
            },
            success: function (data) {
                if (data.result !== 1) {
                    fn.alert({
                        type:"error",
                        title:data.message
                    });
                    return false;
                }
                data = data.data;

                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: appId, // 必填，公众号的唯一标识
                    timestamp: data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: data.noncestr, // 必填，生成签名的随机串
                    signature: data.signature,// 必填，签名，见附录1
                    jsApiList: apiList //['chooseWXPay'] 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });
                cb(wx);
            }
        });
    };
    fn.wxPhoto = function (options) {
        //按钮id
        var fn = window.ABUS.Fn;
        var cb = options.success ? options.success : function () {

        };
        var size = options.size ? options.size : 1;
        fn.getSign({
            apiList : ['chooseImage','uploadImage']
        },function (wx) {
            wx.ready(function () {
                wx.chooseImage({
                    count: size, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        for(var i in localIds){
                            wx.uploadImage({
                                localId: localIds[i], // 需要上传的图片的本地ID，由chooseImage接口获得
                                success: function (res1) {
                                    var serverId = res1.serverId; // 返回图片的服务器端ID
                                    cb(localIds, serverId);
                                }
                            });
                        }
                    }
                });
            });
            wx.error(function (res) {
                console.log('photo error');
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });
        });

    }
});


